//
//  LDWebViewController.m
//  指乎
//
//  Created by Dean on 2016/12/21.
//  Copyright © 2016年 Dean. All rights reserved.
//
#import "LDWebViewController.h"
#import "LBXPermission.h"
#import "LBXPermissionSetting.h"
#import <SDWebImageDownloader.h>
#import <WebKit/WebKit.h>
#import "UIViewController+HBD.h"

@interface NSURLRequest(DataController)

@end
@implementation NSURLRequest(DataController)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
    return YES;
}
@end
@interface LDWebViewController ()<IMYWebViewDelegate ,WKScriptMessageHandler>
{
    
}

@property (nonatomic)BOOL isPopController;

@property (nonatomic)BOOL isAddBottomAD;

@property (nonatomic, strong)NSString *urlPageLastPathName;
@property (nonatomic, strong)NSDictionary *sourceDict;
@property (nonatomic, strong)UIBarButtonItem *navigationCloseBarButtonItem;
@property (nonatomic, strong)UIBarButtonItem *navigationBackBarButtonItem;

//@property (nonatomic, strong)YYAnimatedImageView *loadingAnmView;

@end

@implementation LDWebViewController

- (instancetype)init {
    if (self = [super init]) {
        _isUsedToken = YES;
        self.statusColor = 1;
        self.whiteNavBG = YES;
    }
    return self;
}
-(instancetype)initWithPath:(NSString *)url {
    if (self = [super init]) {
        _requestURL = url;
        _isUsedToken = YES;
        self.statusColor = 1;
        self.whiteNavBG = YES;
    }
    return self;
}
- (UIBarButtonItem *)navigationBackBarButtonItem{
    if (!_navigationBackBarButtonItem) {
        NSString *str = nil;
        if (self.whiteNavBG) {
            str = @"black_back_icon";
        }else{
            str = @"back_white_icon";
        }
        _navigationBackBarButtonItem = [UIBarButtonItem qmui_itemWithImage:kImage(str) target:self action:@selector(backActionForNavigation:)];
    }
    return _navigationBackBarButtonItem;
}
-(void)setupNavigationItems {
    [super setupNavigationItems];
    [self setNavStyleRedAndBackBtn];
    
    if (self.isHiddenNav) {
        self.hbd_barAlpha = 0;
        self.hbd_barHidden = YES;
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        self.navigationItem.hidesBackButton = YES;
//        self.webView.frame = [UIScreen mainScreen].bounds;
        self.webView.frame = CGRectMake(0, 0, self.view.frame.size.width, SCREEN_HEIGHT-(IS_IPHONEX?20:0));
        self.webView.backgroundColor = UIColorWhite;
        
//        adjustsScrollViewInsets_NO(self.webView.scrollView, self);
//        self.edgesForExtendedLayout = UIRectEdgeAll;
        self.navigationItem.leftBarButtonItems = nil;
        //        [self.navigationItem setLeftBarButtonItems:@[[UIBarButtonItem qmui_itemWithImage:nil target:self action:nil]] animated:NO];
        //        [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-200, 0) forBarMetrics:UIBarMetricsDefault];
    } else {
        if (self.webView.canGoBack) {
            [self.navigationItem setLeftBarButtonItems:@[self.navigationBackBarButtonItem, self.navigationCloseBarButtonItem] animated:NO];
        }else{
            self.navigationItem.leftBarButtonItems = @[self.navigationBackBarButtonItem];
        }
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];

    _webView = [[IMYWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, SCREEN_HEIGHT-NavBarHeight)];
    _webView.delegate = self;
    [self.view addSubview:_webView];
    
    if (_requestURL) {
        if ([_requestURL isKindOfClass:[NSString class]]) {
//            NSString *hotStr = [_requestURL componentsSeparatedByString:@"?"].firstObject;
//            [RemoteLogManage event:@"H5Web" label:R(hotStr)];
        }else {
            _requestURL = [NSString stringWithFormat:@"%@",_requestURL];
        }
    }
    [self setWKWebViewUserAgent];
 
    NSLog(@"URL --- %@",_requestURL);
    NSURL * URL = [NSURL URLWithString:_requestURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    
    if (self.headerRequest) {
        for (NSString *key in self.headerRequest.allKeys) {
            NSString *value = self.headerRequest[key];
            [request addValue:value forHTTPHeaderField:key];
        }
    }
//    [self addWkwebView:self.webView.realWebView swipeBackAble:YES];
    [_webView loadRequest:request];

    //登录
    [_webView addScriptMessageHandler:self name:@"lztLoginAction"];
    [_webView addScriptMessageHandler:self name:@"backApp"];
    


//    if (_navColor) {
//        [self setNavColor:_navColor];
//    }
    if (_preNavTitle) {
        self.title = _preNavTitle;
    }
    if (_navTitle) {
        self.title = _navTitle;
    }
    [self.webView.realWebView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:NULL];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshWebView) name:LZT_ReloadWebView object:nil];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webOnResume) name:@"webRefresh" object:nil];

//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkIsTablBaoAuthorWithType) name:KNotificationWithCheckIsTaoBaoAuthord object:nil];
    
}

- (void)webOnResume {
    [self.webView evaluateJavaScript:@"onResume()" completionHandler:^(id xxxx, NSError *error) {
        
    }];
}
- (void)setWKWebViewUserAgent {
    ///增加UserAgent
     if (@available(iOS 12.0, *)){
          NSString *baseAgent = [self.webView.realWebView valueForKey:@"applicationNameForUserAgent"];
         NSString *userAgent = [NSString stringWithFormat:@"%@;appId;iosApp",baseAgent];
         [self.webView.realWebView setValue:userAgent forKey:@"applicationNameForUserAgent"];
     }else
     {
         WEAK
         [self.webView.realWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
             STRONG
                    NSString *oldAgent = result;
                    if (![oldAgent containsString:@"appId"]) {
            //            // 给User-Agent添加额外的信息
                        NSString *newAgent = [NSString stringWithFormat:@"%@;%@;iosApp", oldAgent, @"appId"];
                        // 设置global User-Agent
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newAgent, @"UserAgent", nil];
                        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
                        [self.webView.realWebView setCustomUserAgent:newAgent];
                    }
                }];
     }
}

- (void)refreshWebView {
    [self.webView reload];
}

#pragma mark - ......::::::: WKScriptMessageHandler :::::::......
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
   
    if ([message.name isEqualToString:@"lztNewPageLoad"]) {
        if (message.body) {
               NSDictionary *dict  = [NSDictionary jsonToObject:message.body];
               if ([dict isKindOfClass:[NSDictionary class]]) {
                    if (dict && dict[@"url"] && [dict[@"url"] isKindOfClass:[NSString class]]) {
                       LDWebViewController *vv  = [[LDWebViewController alloc] initWithPath:dict[@"url"]];
                       vv.isUsedToken = NO;
                       [self popSelf:self pushViewController:vv];
                   }
                
               }
        }
        
    }
   
    // 返回
    if([message.name isEqualToString:@"backApp"]){
        [self popBackAction];
    }
    
    
    // web跳转到原生
    if([message.name isEqualToString:@"webJumpPhone"]){
        if (message.body) {
            NSDictionary *dict  = [NSDictionary jsonToObject:message.body];
            if ([dict isKindOfClass:[NSDictionary class]]) {
                NSString *action = dict[@"pageName"];
                if ([action isEqualToString:@"lztLoginAction"]) {
                   
                } else if ([action containsString:@"zl://app/liveRoom"]) {
                    // 进入直播间
                    
                }
            }
        }
    }
   
    if ([message.name isEqualToString:@"routeBack"]) {
        if (self.webView.canGoBack) {
            [self.webView goBack];
        }else {
            [self popBackAction];
        }
    }
   
    else if([message.name isEqualToString:@"lztCustomTitle"]){
        if (message.body) {
            self.sourceDict = [NSDictionary jsonToObject:message.body];
            if (self.sourceDict && self.sourceDict.count > 0) {
                [self showRightBarButtonTitle:R(self.sourceDict[@"title"]) selector:@selector(cusTomAction:)];
            }
        }
    }
    if([message.name isEqualToString:@"closeWebView"]){
        [self popBackAction];
    }
}

- (void)cusTomAction:(id)sender {
    if (self.sourceDict && [self.sourceDict isKindOfClass:[NSDictionary class]] ) {
        if (self.sourceDict.count == 0) {
            return;
        }
        LDWebViewController *push = [[LDWebViewController alloc] initWithPath:self.sourceDict[@"url"]];
        push.navTitle = self.sourceDict[@"title"];
        [self.navigationController pushViewController:push animated:YES];
    }
}

- (void)loadWithUrlStr:(NSString*)urlStr
{
    if (urlStr.length > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSURLRequest *webRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]
                                                        cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                                    timeoutInterval:30];
            [self.webView loadRequest:webRequest];
            [self.webView reload];
        });
    }else {
//        [self.webView reload];
    }
}
- (BOOL)webView:(IMYWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(WKNavigationType)navigationType{
//    NSString *url = [request.URL.absoluteString stringByRemovingPercentEncoding];
//
//    NSString * scheme = request.URL.scheme;

    return YES;
}


- (void)webViewDidFinishLoad:(IMYWebView*)webView {
    [self updateNavbarItem];
    if (!self.isHiddenNav) {
        if (_navTitle) {
            self.title = _navTitle;
        }else{
            self.title = [webView title];
        }
    }
    [self removeLoading];
}
- (void)webViewTitleChange:(NSString *)title
{
    if (!self.isHiddenNav && !_navTitle) {
        self.title = title;
    }
}
- (void)removeLoading{
    [TGProgressHUD dismissMPHUD];
//    if (self.loadingAnmView.superview!=nil) {
//        [self.loadingAnmView removeFromSuperview];
//    }
    
}
- (void)webViewDidFinishLoad:(IMYWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [self updateNavbarItem];
    [self removeLoading];

}
- (void)webView:(IMYWebView *)webView didFailLoadWithError:(NSError *)error {
    [self removeLoading];
}
-(UIStatusBarStyle)preferredStatusBarStyle;
{
    if (self.whiteNavBG) {
        return UIStatusBarStyleDefault;
    }
    if (self.statusColor == 0) {
        return UIStatusBarStyleLightContent;
    }else {
        return UIStatusBarStyleDefault;
    }
}
- (void)updateNavbarItem{
    if (self.isHiddenNav) {
        self.navigationItem.hidesBackButton = YES;
        self.navigationItem.leftBarButtonItem = nil;
        self.navigationItem.leftBarButtonItems = nil;
//        [self.navigationItem setLeftBarButtonItems:@[[UIBarButtonItem qmui_itemWithImage:nil target:self action:nil]] animated:NO];
//        WKWebView *webView = self.webView.realWebView;
//        if (self.webView.canGoBack) {
//            self.disableRightSwipe = YES;
//            webView.allowsBackForwardNavigationGestures = YES;
//        }else {
//            self.disableRightSwipe = NO;
//            webView.allowsBackForwardNavigationGestures = NO;
//        }
    }else {
        if (self.webView.canGoBack) {
            [self.navigationItem setLeftBarButtonItems:@[self.navigationBackBarButtonItem, self.navigationCloseBarButtonItem] animated:NO];
        }else{
            [self.navigationItem setLeftBarButtonItems:@[self.navigationBackBarButtonItem] animated:NO];
        }
    }
    
}
- (UIBarButtonItem *)navigationCloseBarButtonItem {
    if (_navigationCloseBarButtonItem) return _navigationCloseBarButtonItem;
        _navigationCloseBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:0 target:self action:@selector(navigationIemHandleClose:)];

    return _navigationCloseBarButtonItem;
}
- (void)backActionForNavigation:(id)sender{
    if ([_webView canGoBack]) {
        [_webView goBack];
        return;
    }
    
    if (self.isPresent) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)navigationIemHandleClose:(id)sender {
    
    if (self.isPresent) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark KVO的监听代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

   if ([keyPath isEqualToString:@"canGoBack"])
    {
        [self updateNavbarItem];
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)popBackAction{
    if (!self.isPopController) {
        self.isPopController = YES;
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)dealloc
{
    NSLog(@"webView dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.webView.realWebView removeObserver:self forKeyPath:@"canGoBack"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.webView evaluateJavaScript:@"onResume()" completionHandler:^(id xxxx, NSError *error) {
        
    }];
    [self hbd_setNeedsUpdateNavigationBar];
    if (self.isHiddenNav) {
        self.fd_prefersNavigationBarHidden = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}


@end
